package cn.qu.dockman.mgr.service.impl;

import cn.qu.dockman.mgr.entity.Container;
import cn.qu.dockman.mgr.entity.Env;
import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.example.ContainerExample;
import cn.qu.dockman.mgr.example.EnvExample;
import cn.qu.dockman.mgr.example.HostExample;
import cn.qu.dockman.mgr.mapper.ContainerMapper;
import cn.qu.dockman.mgr.mapper.EnvMapper;
import cn.qu.dockman.mgr.mapper.HostMapper;
import cn.qu.dockman.mgr.resp.EnvBean;
import cn.qu.dockman.mgr.service.EnvService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by zh on 17/3/7.
 */
@Service
public class EnvServiceImpl implements EnvService {
    @Autowired
    private EnvMapper envMapper;
    @Autowired
    private HostMapper hostMapper;
    @Autowired
    private ContainerMapper containerMapper;

    @Override
    public List<EnvBean> findEnvs() {
        List<EnvBean> envBeanList = new ArrayList<>();
        List<Env> envList = envMapper.selectByExample(new EnvExample());
        for (Env env : envList) {
            EnvBean bean = new EnvBean();
            bean.setEnv(env);

            List<Host> hostList = hostMapper.selectByExample(new HostExample() {{
                createCriteria().andEnvIdEqualTo(env.getId());
            }});
            if (!hostList.isEmpty()) {
                List<Integer> hostIds = hostList.stream().map(Host::getId).collect(Collectors.toList());
                List<Container> containerList = containerMapper.selectByExample(new ContainerExample() {{
                    createCriteria().andHostIdIn(hostIds);
                }});
                bean.setContainerCount(containerList.size());
            } else {
                bean.setContainerCount(0);
            }
            bean.setHostCount(hostList.size());
            envBeanList.add(bean);
        }
        return envBeanList;
    }

    @Override
    public Env findById(int id) {
        return envMapper.selectByPrimaryKey(id);
    }
}
